//native-usb.cpp
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <fcntl.h>
#include <errno.h>
#include <linux/hdreg.h>


#define LOG_TAG "native_usb"
#include <android/log.h>


#define LOGI(...) \
  ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
#define LOGW(...) \
  ((void)__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
#define LOGE(...) \
  ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))

extern "C" JNIEXPORT jboolean JNICALL Java_com_wes_dsptest_UsbUtils_isHardDiskExist(JNIEnv* env, jobject thiz)
{
    const char* devPath = "/dev/block/sda"; // 检查的硬盘设备节点名
    char cmd[256];
    char result[1024];
    FILE* fp;

    // 组装命令行
    snprintf(cmd, sizeof(cmd), "ls %s", devPath);

    // 执行命令行
    fp = popen(cmd, "r");
    if (fp == NULL) {
        LOGE("Failed to execute command");
        return JNI_FALSE;
    }

    // 读取命令行输出
    memset(result, 0, sizeof(result));
    if (fgets(result, sizeof(result) - 1, fp) == NULL) {
        pclose(fp);
        return JNI_FALSE;
    }

    // 关闭命令行进程
    pclose(fp);

    // 检查命令行输出是否包含硬盘设备节点名
    if (strstr(result, devPath) == NULL) {
        return JNI_FALSE;
    }

    return JNI_TRUE;
}

extern "C" JNIEXPORT jstring JNICALL Java_com_wes_dsptest_UsbUtils_getDiskInfo(JNIEnv *env, jobject obj)
{
    const char *dev_path = "/dev/block/sda";
    int fd = open(dev_path, O_RDONLY | O_NONBLOCK);
    if (fd == -1) {
        LOGI("Error opening device %s: %s", dev_path, strerror(errno));
        return NULL;
    }

    struct hd_driveid hd;
    if (ioctl(fd, HDIO_GET_IDENTITY, &hd) < 0) {
        LOGI("Error ioctl device %s: %s", dev_path, strerror(errno));
        return NULL;
    }
    close(fd);

    char serial_no[21];
    memcpy(serial_no, hd.serial_no, sizeof(hd.serial_no));
    serial_no[sizeof(hd.serial_no)] = '\0';

    char model[41];
    memcpy(model, hd.model, sizeof(hd.model));
    model[sizeof(hd.model)] = '\0';

    char result[256];
    snprintf(result, sizeof(result), "model: %s, serial no: %s", model, serial_no);

    LOGI("reuslt :%s", result);
    return NULL;
}
